package com.banciyuan.bcywebview.biz.picshow;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.fragment.BaseFragment;
import com.banciyuan.bcywebview.utils.file.ByteUtils;
import com.banciyuan.bcywebview.utils.file.FileTypeUtil;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.io.File;

/**
 * Created by squall on 2016/6/12.
 */
public class PicShowFragment extends BaseFragment {

    private WebView mContentWv;
    private ProgressBar loading;
    private ImageLoader imageLoader;
    private String tempPath;
    private String path;
    private int index;
    private boolean isViewShown = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.picshow_layout, null);
        try {
            initArgs();
            initView(view);
            initAction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

    @Override
    protected void initArgs() {
        tempPath = ImageManager.getBigTempFile(getActivity());
        imageLoader = ImageLoader.getInstance();
        path = getArguments().getString("path");
        index = getArguments().getInt("index");
    }

    private void checkStatus() throws Exception {
        ViewPictureActivity2 viewPictureActivity2 = (ViewPictureActivity2) getActivity();
        if (viewPictureActivity2 != null && !viewPictureActivity2.isFinishing()) {
            viewPictureActivity2.checkBtn(index);
        }
    }

    private void initView(View view) {
        mContentWv = (WebView) view.findViewById(R.id.picshow_content_wv);
        loading = (ProgressBar) view.findViewById(R.id.loading);
        loading.setVisibility(View.VISIBLE);
        mContentWv.setVisibility(View.INVISIBLE);
        mContentWv.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mContentWv.setOnTouchListener(new LargeOnTouchListener(mContentWv));
        mContentWv.getSettings().setJavaScriptEnabled(false);
        mContentWv.getSettings().setUseWideViewPort(true);
        mContentWv.getSettings().setLoadWithOverviewMode(true);
        mContentWv.getSettings().setBuiltInZoomControls(true);
        mContentWv.getSettings().setDisplayZoomControls(false);
        mContentWv.getSettings().setSupportZoom(true);
        mContentWv.setVerticalScrollBarEnabled(false);
        mContentWv.setHorizontalScrollBarEnabled(false);
        if (!isViewShown) {
            parseImage(path);
        }

    }

    public void parseImage(final String pathRemote) {
        this.path = pathRemote;
        new AsyncTask<String, String, String>() {
            @Override
            protected String doInBackground(String... voids) {
                try {
                    File file = ImageLoader.getInstance().getDiskCache().get(pathRemote);
                    if (file != null && file.exists()) {
                        if (StringUtil.notNullEqual(new FileTypeUtil().getFileByFile(file), "gif")) {
                            return "file://" + file.getAbsolutePath();
                        } else {
                            return decodeImage(file);
                        }
                    } else {
                        return "";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return "";
                }
            }

            @Override
            protected void onPostExecute(String image) {
                try {
                    if (!TextUtils.isEmpty(image)) {
                        showContent(image);
                    } else if (image.equals("")) {
                        ImageLoader.getInstance().loadImage(path, null, ImageOptions.optionsCopy, new SimpleImageLoadingListener() {
                            @Override
                            public void onDiskCacheComplete(String imageUri, File mfile, String type) {
                                parseImage(imageUri);
                            }
                        }, true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.execute();
    }

    private String decodeImage(File file) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            return ByteUtils.parseEncodeFileToDecode(getActivity(), file, tempPath);
        } else {
            return "error";
        }
    }

    private void showContent(String path) {
        StringBuilder str2 = new StringBuilder();
        str2.append("<html><head><style>html,body{background-color:#000;margin:0;padding:0;}*{-webkit-tap-highlight-color:rgba(0, 0, 0, 0);}</style></head>\n");
        str2.append("<body>\n");
        str2.append("<table style=\"background-color:#000;width: 100%;height:100%; border: 0; margin: 0; padding: 0; border-collapse: collapse; border-spacing: 0;\">\n");
        str2.append("<tr style=\"background-color:#000;width: 100%; border: 0; margin: 0; padding: 0;\">\n");
        str2.append("<td align=\"middle\" align=\"center\" style=\"background-color:#000;width: 100%; border: 0; margin: 0; padding: 0;\">\n");
        str2.append("<div style=\"display:block\">\n");
        str2.append("<img  src=\"" + path + "\" width=\"100%\" style=\"background-color:#000;border: 0; display: block;\" />\n");
        str2.append("</div>\n");
        str2.append("</td>\n");
        str2.append("</tr>\n");
        str2.append("</table>\n");
        str2.append("</body></html>");
        mContentWv.setBackgroundColor(Color.TRANSPARENT);
        mContentWv.loadDataWithBaseURL("file:///android_asset/", str2.toString(), "text/html", "utf-8", null);
        loading.setVisibility(View.GONE);
        mContentWv.setVisibility(View.VISIBLE);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        try {
            if (getView() != null) {
                isViewShown = true;
                if (isVisibleToUser) {
                    checkStatus();
                }
            } else {
                isViewShown = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class LargeOnTouchListener implements View.OnTouchListener {

        GestureDetector gestureDetector;

        public LargeOnTouchListener(final View view) {
            gestureDetector = new GestureDetector(view.getContext(),
                    new GestureDetector.SimpleOnGestureListener() {
                        @Override
                        public boolean onSingleTapConfirmed(MotionEvent e) {
                            if (getActivity() != null) {
                                getActivity().finish();
                            }
                            return true;
                        }
                    });
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            gestureDetector.onTouchEvent(event);
            return false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mContentWv != null) {
            mContentWv.destroy();
        }
    }
}
